<template>
    <view class="content">
        <uv-vtabs :chain="chain" :list="getList" :height="height" hdHeight="120rpx" @change="change">
            <template v-for="(item,index) in getList" :key="index">
                <uv-vtabs-item :index="index">
                    <view class="uitxit">{{item.name}}</view>
                    <view class="item" v-for="(item2,index2) in item.childrens" :key="index2" v-if="item.childrens.length>0">
                        <image class="product-image" :src="imgUrl+item2.pro_pic" />
                        <view class="product-info">
                            <view class="product-name">{{item2.pro_name}}</view>
							<view class="productsfa">
								<view class="text-price">{{item2.sale_price}}</view>
								<view class="product-bottom">
								    <view class="counter" v-if="item2.count && item2.count > 0">
								        <image src="/static/sjimg/jin.png" @click="decreaseCount(item2)" class="jiacss"/>
								        <text class="tjxt">{{item2.count}}</text>
								        <image src="/static/sjimg/add.png" @click="increaseCount(item2)" class="jiacss"/>
								    </view>
								    <image src="/static/sjimg/add.png" @click="addProduct(item2)" v-else  class="jiacss"/>
								</view>
							</view>
                        </view>
                    </view>
                    <view class="imghubox" v-else>
                        <image src="/static/sjimg/nos.png" mode="scaleToFill" class="imgnos"></image>
                    </view>
                </uv-vtabs-item>
            </template>
        </uv-vtabs>
        <view class="cart-bar">
            <view class="cartcontent">
                <view class="shanpin" @click="lookProduct"> 
                    <uni-icons type="cart" size="20"></uni-icons>
                    <text class="txts" v-if="pronum<=0">暂无商品</text>
                    <view v-else class="mrop">
                        <text class="txts">× {{pronum}} 件商品</text>
                        <text class="text-price">{{money}}</text>
                    </view>
                </view>
                <view class="btns" @click="xiadan"> 购买 </view>
            </view>
        </view>
        <uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="20px 20px 0 0">
            <view class="logins">
                <view class="cantxt">
                    <text>购物车</text>
                    <text class="clear" @click="delkon">清空</text>
                </view>
                <scroll-view scroll-y="true" class="scrollviewes">
                    <view class="cart-item" v-for="(item, index) in cartList" :key="index">
                        <image class="item-image" :src="imgUrl+item.pro_pic" mode="scaleToFill"/>
                        <view class="item-info">
                            <view class="yusi">
                                <view class="item-header">{{item.pro_name}}</view>
                                <uni-tag text="删除" size="mini" @click="del(item)"/>
                            </view>
                            <view class="item-bottom">
                                <text class="text-price">{{item.sale_price}}</text>
                                <uni-number-box :value="item.count" :step="1" :min="1" @change="(val) => updateCount(item, val)"/>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </uni-popup>
    </view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue';
	import { onShow , onLoad } from '@dcloudio/uni-app';
	import { apiProlists , apiProlist , apiDosave , apiBuy } from '@/api/upapi.js';

	const getList = ref([]);
	const cartList = ref([]);
	const mid =ref('');
	const memberId=ref('');
	const popup =ref(null);
	const money =ref('');
	const chain = ref(true);
	const height = ref(0);
	const pronum = ref(0);
	const imgUrl = ref('https://i.73cc.com:9555/unipay/upload/');

	const lookProduct = ()=>{
		if(pronum.value>0){
			popup.value.open();
		}else{
			uni.showToast({ title:'请添加商品',icon:'none' });
		}
	};
	const del = (e) => {
		const indexToDelete = cartList.value.findIndex(item => item.id === e.id);
		if (indexToDelete!== -1) {
			cartList.value.splice(indexToDelete, 1);
			pronum.value = cartList.value.reduce((sum, item) => sum + item.count, 0);
			money.value = cartList.value.reduce((allmoney, item) => allmoney + (item.sale_price * item.count), 0);
			const targetProduct = findProductInList(e.id);
			if (targetProduct) {
				targetProduct.count = 0;
			}
		}
	};
	
	const xiadan = async()=>{
		if(pronum.value<=0){ uni.showToast({ title: '请添加商品', icon: 'none' }); return };
		const newArray = cartList.value.map(item => {
		    return {
		        pro_name: item.pro_name,
		        count: item.count,
		        pro_pic: item.pro_pic,
		        id: item.id,
		        sale_price: item.sale_price
		    };
		});
		uni.navigateTo({ url: `/pagesA/business/mealDedails?data=${JSON.stringify(newArray)}&money=${money.value}&mids=${mid.value}` });
		pronum.value=0;
		money.value=0; 
		cartList.value=[]; 
		getList.value.forEach(category => {
			category.childrens.forEach(product => {
				product.count = 0;
			});
		});
	};
	const delkon =()=>{ 
		pronum.value=0; 
		money.value=0; 
		cartList.value=[]; 
		getList.value.forEach(category => {
			category.childrens.forEach(product => {
				product.count = 0;
			});
		});
		popup.value.close(); 
	};
	const calculateHeight = () => { return uni.getSystemInfoSync().windowHeight - uni.upx2px(120) };
	const addProduct = (product) => {
		const existingItemIndex = cartList.value.findIndex(cartItem => cartItem.id === product.id);
		if (existingItemIndex!== -1) {
			cartList.value[existingItemIndex].count++;
		} else {
			product.count = 1;
			cartList.value.push({...product });
		}
		pronum.value = cartList.value.reduce((sum, item) => sum + item.count, 0);
		money.value = cartList.value.reduce((allmoney, item) => allmoney + (item.sale_price * item.count), 0);
	};
	const increaseCount = (product) => {
		const existingItemIndex = cartList.value.findIndex(cartItem => cartItem.id === product.id);
		if (existingItemIndex!== -1) {
			cartList.value[existingItemIndex].count++;
			product.count = cartList.value[existingItemIndex].count;
		} else {
			product.count = 1;
			cartList.value.push({...product });
		}
		pronum.value = cartList.value.reduce((sum, item) => sum + item.count, 0);
		money.value = cartList.value.reduce((allmoney, item) => allmoney + (item.sale_price * item.count), 0);
	};
	const decreaseCount = (product) => {
		const existingItemIndex = cartList.value.findIndex(cartItem => cartItem.id === product.id);
		if (existingItemIndex!== -1) {
			if (cartList.value[existingItemIndex].count > 1) {
				cartList.value[existingItemIndex].count--;
				product.count = cartList.value[existingItemIndex].count;
			} else {
				cartList.value.splice(existingItemIndex, 1);
				product.count = 0;
			}
			pronum.value = cartList.value.reduce((sum, item) => sum + item.count, 0);
			money.value = cartList.value.reduce((allmoney, item) => allmoney + (item.sale_price * item.count), 0);
		}
	};
	const updateCount = (item, val) => {
		const existingItemIndex = cartList.value.findIndex(cartItem => cartItem.id === item.id);
		if (existingItemIndex!== -1) {
			cartList.value[existingItemIndex].count = val;
			const targetProduct = findProductInList(item.id);
			if (targetProduct) {
				targetProduct.count = val;
			}
			pronum.value = cartList.value.reduce((sum, item) => sum + item.count, 0);
			money.value = cartList.value.reduce((allmoney, item) => allmoney + (item.sale_price * item.count), 0);
		}
	};
	const findProductInList = (id) => {
		for (const category of getList.value) {
			for (const product of category.childrens) {
				if (product.id === id) {
					return product;
				}
			}
		}
		return null;
	};
	const initData = async() =>{
		try {
			let res = await apiProlists({mid:mid.value});
			if(res.data.result==0){
				getList.value=res.data.object;
				getList.value.forEach(category => {
					category.childrens.forEach(product => {
						product.count = 0;
					});
				});
			}
		} catch (error) {
			console.error('获取数据失败', error);
		}
	};

	onLoad((option) => {
		uni.setNavigationBarTitle({ title: option.title });
		const mervalue = uni.getStorageSync('xwmemberId');
		mid.value= option.mid;
		if(!mervalue){
			uni.showToast({ title: '请先登录',icon:'none' });
			setTimeout(() => {
				uni.switchTab({ url:'/pages/index/my' })
			}, 1000);
			return
		}else{
			memberId.value=mervalue
			initData();
		}
	});

	const change = (index) => {
		console.log('选项改变：', index)
	};

	height.value = calculateHeight();
</script>    
<style scoped lang="scss">
	.uitxit {
	    padding: 10rpx 30rpx;
	    font-size: 24rpx;
	    font-weight: bold;
	    color: #999;
	}
	.counter{
		display: flex;
		align-items: center;
		.tjxt{
			font-size: 28rpx;
			margin: 0 20rpx;
			color: #646464;
		}
	}
	.jiacss{
		width: 45rpx;
		height: 45rpx;
	}
	.uitxit::before {
	    content: '';
	    display: inline-block;
	    width: 8rpx;
	    height: 0.8em;
	    border-radius: 10rpx;
	    background-color: #999;
	    margin-right: 10rpx; /* 可以根据需要调整间距 */
	}
	.imghubox{
		display: flex;
		justify-content: center;
		.imgnos{
			width: 140rpx;
			height: 112rpx;
		}
	}
	.item {
		display: flex;
		padding: 10rpx 20rpx;
		&-title {
			.text {
				font-weight: 700;
				font-size: 32rpx;
				color: #111;
			}
		}
		&-content {
			padding: 20rpx 0;
			.text {
				line-height: 48rpx;
				font-size: 30rpx;
				color: #111;
				/* #ifndef APP-NVUE */
				word-break: break-all;
				/* #endif */
			}
		}
		.product-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			background-color: #f1f6f3;
		}
		
		.product-info {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			flex: 1;
			margin-left: 24rpx;
			
			.product-name {
				font-size: 30rpx;
				color: #3b3b3b;
			}
			.productsfa{
				display: flex;
				align-items: center;
				justify-content: space-between;
				.text-price {
					color: #ff4a82;
					font-size: 32rpx;
				}
				
				.text-price::before {
					content: '￥';
					color: #ff4a82 !important;
					font-size: 24rpx !important;
				}
			}
			.product-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
		}
	}
	.gap {
		padding: 0 30rpx;
	}
	.cart-bar {
		height: 98rpx;
		background-color: #fff;
		border-top: 2rpx solid #dddddd;
		display: flex;
		z-index: 8;
		.cartcontent{
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			.shanpin{
				display: flex;
				align-items: center;
				margin-left: 30rpx;
				.txts{
					margin-left: 20rpx;
					color: #666;
					font-size: 26rpx;
				}
				.mrop{
					display: flex;
					align-items: center;
				}
			}
			.btns{
				font-size: 26rpx;
				background-color: #ff4a82;
				color: #fff;
				padding:20rpx 50rpx;
				border-radius: 60rpx;
				margin-right: 30rpx;
			}
			.text-price {
				color: #ff4a82;
				font-size: 28rpx;
				margin-left: 20rpx;
			}
			
			.text-price::before {
				content: '￥';
				color: #ff4a82 !important;
				font-size: 22rpx !important;
			}
			.imgst{
				width: 60rpx;
			}
		}
	}
	.logins{
		background-color: #fff;
		padding: 30rpx 30rpx 120rpx;
		border-radius: 30rpx 30rpx 0 0;
		display: flex;
		flex-direction: column;
		.cantxt{
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			padding-bottom: 20rpx;
			border-bottom: 2rpx solid #ececec;
		}
	}
	.scrollviewes {
		height: 500rpx;
		.cart-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			
			.item-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 20rpx;
			}
			
			.item-info {
				flex: 1;
				display: flex;
				height: 120rpx;
				flex-direction: column;
				justify-content: space-between;
				.yusi{
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
				.item-header {
					font-size: 24rpx;
					color: #999;
				}
				
				.item-bottom {
					display: flex;
					justify-content: space-between;
					align-items: end;
					margin-top: 20rpx;
					
					.text-price {
						color: #ff4a82;
						font-size: 28rpx;
					}
					
					.text-price::before {
						content: '￥';
						color: #ff4a82 !important;
						font-size: 22rpx !important;
					}
				}
			}
		}
	}
</style>